package com.egao.common.publicly;

import cn.hutool.core.util.StrUtil;
import com.egao.common.component.wechat.WeChatUtils;
import com.egao.common.core.Constants;
import com.egao.common.core.log.LogWechat;
import com.egao.common.core.security.JwtUtil;
import com.egao.common.core.web.JsonResult;
import com.egao.common.module.system.entity.LoginRecord;
import com.egao.common.module.system.entity.User;
import com.egao.common.module.system.service.LoginRecordService;
import com.egao.common.module.system.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * 微信企业号
 * @author lym
 */
@Api(tags = "微信企业号")
@RestController
@RequestMapping("${api}")
public class PubliclyWeChatController {

    @Resource
    private UserService userService;
    @Resource
    private LoginRecordService loginRecordService;

    @ApiOperation("微信企业号登录")
    @GetMapping("/publicly/wechat/login/{code}")
    public JsonResult login(HttpServletRequest request, @PathVariable String code) {
        if (StrUtil.isBlank(code)) {
            LogWechat.error("没有授权码");
            return JsonResult.error("没有授权码");
        }

        // 企业号查询用户
        String username = WeChatUtils.getStudent(code);
        if (StrUtil.isBlank(username)) {
            LogWechat.error("未查询到用户: " + username);
            return JsonResult.error("未查询到用户");
        }

        User user = userService.getByUsername(username);
        if (user == null) {
            LogWechat.error("用户不存在: " + username);
            return JsonResult.error("用户不存在");
        }

        // 查询用户权限
        user = userService.selectUserAuth(user);

        // 授权
        UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(
                user, null, user.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authentication);

        // 构造token
        String accessToken = JwtUtil.buildToken(username, Constants.TOKEN_EXPIRE_TIME, Constants.TOKEN_KEY);
        loginRecordService.saveAsync(username, LoginRecord.TYPE_REFRESH, "企业号登录", request);
        LogWechat.info("企业号登录: " + username);

        return JsonResult.ok().setData(accessToken);
    }

}
